//
//  WCNCaseDetailVC.m
//  WCN
//
//  Created by 杨鑫 on 15/6/12.
//  Copyright (c) 2015年 ShanghaiCize Trade And Business Co., Ltd. All rights reserved.
//

#import "WCNCaseDetailVC.h"
#import "WCNWoundDetailVC.h"
#import "WCNCareRecordDetailVC.h"
//
#import "WCNCaseItemTCell.h"
#import "WCNCaseItemNoImgTCell.h"
#import "WCNCaseDayTHFV.h"
//
#import "MJRefresh.h"
//
#import "NSString+Utilities.h"
#import "UILabel+Utilities.h"
//
#import "WCPopupLayerManager.h"
#import "WCNetworkAccessManager.h"
#import "WCImageManager.h"
#import "WCNPListFileDataStore.h"
#import "CareCase.h"
//
#import "Macros.h"
#import "Constants.h"

static NSString *cellId = @"WCNCaseItemTCell";
static NSString *cell2Id = @"WCNCaseItemNoImgTCell";
static NSString *headerId = @"WCNCaseDayTHFV";

@interface WCNCaseDetailVC ()<UITableViewDataSource, UITableViewDelegate>

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *dayLineLeadingToSuper;
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (strong, nonatomic) NSString *url;
@property (strong, nonatomic) NSString *filePath;
@property (strong, nonatomic) NSArray *detail;
@property (strong, nonatomic) NSMutableDictionary *typeStrs;
@property (strong, nonatomic) NSMutableDictionary *contents;

@end

@implementation WCNCaseDetailVC

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.title = @"详情";

        _typeStrs = [NSMutableDictionary dictionary];
        _contents = [NSMutableDictionary dictionary];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.dayLineLeadingToSuper.constant -= kOnePX;
    
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    [self.tableView registerNib:[UINib nibWithNibName:cellId bundle:nil] forCellReuseIdentifier:cellId];
    [self.tableView registerNib:[UINib nibWithNibName:cell2Id bundle:nil] forCellReuseIdentifier:cell2Id];
    [self.tableView registerClass:[WCNCaseDayTHFV class] forHeaderFooterViewReuseIdentifier:headerId];
    
    __weak typeof(self) weakSelf = self;
    [self.tableView addLegendHeaderWithRefreshingBlock:^{
        [weakSelf refresh];
    }];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if ([[WCNPListFileDataStore shareStore] hasFile:self.filePath]) {
        self.detail = [[WCNPListFileDataStore shareStore] readArrayFromFile:self.filePath];
    }
    
    if ([[WCNetworkAccessManager sharedMg] timeSinceLastUrl:self.url] > 2*kUrlCD) {
        MBProgressHUD *hud = [[WCPopupLayerManager shareMg] showSimple:self.navigationController.view];
        [[WCNetworkAccessManager sharedMg] GET:self.url parameters:nil success:^(NSDictionary *result){
            NSArray *caseDetail = result[@"data"];
            self.detail = [[WCNPListFileDataStore shareStore] saveCareRecords:caseDetail toFile:self.filePath success:nil];
            [self.tableView reloadData];
        } failure:nil netError:nil always:^{
            [hud hide:YES];
        }];
    }
}

- (void)refresh
{
    [[WCNetworkAccessManager sharedMg] GET:self.url parameters:nil success:^(NSDictionary *result){
        NSArray *caseDetail = result[@"data"];
        self.detail = [[WCNPListFileDataStore shareStore] saveCareRecords:caseDetail toFile:self.filePath success:nil];
        [self.tableView reloadData];
    } failure:nil netError:nil always:^{
        [self.tableView.header endRefreshing];
    }];
}

#pragma mark - Setter

- (void)setCareCase:(CareCase *)careCase
{
    _careCase = careCase;
    _url = [NSString stringWithFormat:@"template/nursing/task/list/%@", careCase.stringId];
    
    NSString *fileName = [NSString stringWithFormat:@"case%@.plist", careCase.stringId];
    self.filePath = [[WCNPListFileDataStore shareStore] careTemplatePath:fileName];
}

#pragma mark - Getter

- (NSString *)careCaseTitle:(NSDictionary *)data
{
    NSString *type = data[@"type"];
    if ([@"WOUND_ADD_RECORD" isEqualToString:type]) {
        return @"新增伤口记录";
    } else if ([@"WOUND_NURSING_RECORD" isEqualToString:type]) {
        return @"伤口护理记录";
    }
    return @"";
}

- (NSString *)careCaseContent:(NSDictionary *)data
{
    NSString *desc = @"用药:";
    NSArray *medicines = data[@"medicines"];
    for (NSDictionary *medicine in medicines) {
        desc = [NSString stringWithFormat:@"%@ %@", desc, medicine[@"name"]];
    }
    return desc;
}

#pragma mark - <UITableViewDataSource, UITableViewDelegate>

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dayItem = self.detail[indexPath.section][indexPath.row];
    NSString *type = dayItem[@"type"];
    if ([@"WOUND_ADD_RECORD" isEqualToString:type]) {
        WCNWoundDetailVC *vc = [[WCNWoundDetailVC alloc] initWith:dayItem mode:WCNWoundDetailVCModeScan];
        [self.navigationController pushViewController:vc animated:YES];
    } else if ([@"WOUND_NURSING_RECORD" isEqualToString:type]) {
        WCNCareRecordDetailVC *vc = [[WCNCareRecordDetailVC alloc] initWith:dayItem];
        [vc setImagesDir:WCImageTypeImage];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.detail.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *day = self.detail[section];
    return day.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dayItem = self.detail[indexPath.section][indexPath.row];
    NSArray *imgs = dayItem[@"images"];
    if (imgs.count > 0) {
        return 114;
    } else {
        return 59;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dayItem = self.detail[indexPath.section][indexPath.row];
    NSArray *imgs = dayItem[@"images"];
    if (imgs.count > 0) {
        WCNCaseItemTCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId forIndexPath:indexPath];
        
        if ([self.typeStrs objectForKey:indexPath]) {
            cell.careCaseTitle.text = [self.typeStrs objectForKey:indexPath];
        } else {
            NSString *typeStr = [self careCaseTitle:dayItem];
            cell.careCaseTitle.text = typeStr;
            
            [self.typeStrs setObject:typeStr forKey:indexPath];
        }
        if ([self.contents objectForKey:indexPath]) {
            cell.careCaseContent.text = [self.contents objectForKey:indexPath];
        } else {
            NSString *content = [self careCaseContent:dayItem];
            cell.careCaseContent.text = content;
            
            [self.contents setObject:content forKey:indexPath];
        }
        
//        if (!tableView.dragging && !tableView.decelerating) {
            [cell setImgs:imgs];
//        }
        
        return cell;
    } else {
        WCNCaseItemNoImgTCell *cell = [tableView dequeueReusableCellWithIdentifier:cell2Id forIndexPath:indexPath];
        
        if ([self.typeStrs objectForKey:indexPath]) {
            cell.careCaseTitle.text = [self.typeStrs objectForKey:indexPath];
        } else {
            NSString *typeStr = [self careCaseTitle:dayItem];
            cell.careCaseTitle.text = typeStr;
            
            [self.typeStrs setObject:typeStr forKey:indexPath];
        }
        if ([self.contents objectForKey:indexPath]) {
            cell.careCaseContent.text = [self.contents objectForKey:indexPath];
        } else {
            NSString *content = [self careCaseContent:dayItem];
            cell.careCaseContent.text = content;
            
            [self.contents setObject:content forKey:indexPath];
        }
        
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 22;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    WCNCaseDayTHFV *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:headerId];
    NSDictionary *dayItem = self.detail[section][0];
    header.titleLabel.text = [NSString stringWithFormat:@"Day%ld", (long)[dayItem[@"targetDay"] integerValue]];
    return header;
}

#pragma mark - UITableViewDelegate extend UIScrollViewDelegate

//- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
//{
//    if (!decelerate)
//    {
//        [self loadImagesForOnscreenRows];
//    }
//}
//
//- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
//{
//    [self loadImagesForOnscreenRows];
//}
//
//- (void)loadImagesForOnscreenRows
//{
//    NSArray *visiblePaths = [self.tableView indexPathsForVisibleRows];
//    for (NSIndexPath *indexPath in visiblePaths) {
//        
//    }
//}

@end
